package com.itlong.cloud.controller.sdkV1.old;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.VO.sdk.SDKServerUserCacheVO;
import com.itlong.cloud.POJO.VO.sdk.old.SDKAppOldUserInfoCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.APPDeviceTypeEnum;
import com.itlong.cloud.enumerate.SystemTypeEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppOldRegisterServiceClient;
import com.itlong.cloud.user.sdk.ISDKAppOldUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * <desc>
 *      sdk-App端登录/登出Controller
 * </desc>
 *
 * @createDate 2017/10/26
 */
@RestController
@RequestMapping("/jiabanjing/interface")
public class SDKAppOldLoginController {

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    @Autowired
    IAppOldRegisterServiceClient iAppOldRegisterServiceClient;

    @Autowired
    ISDKAppOldUserServiceClient isdkAppOldUserServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;


    /**
     * <desc>
     *    APP SDK_登录.
     * </desc>
     *
     * @param appid 应用接入凭证
     * @param appsecret 应用接入密钥
     * @param phoneNo 用户手机号
     * @param loginDevice 用户登录设备类型（android/ios）
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-06
     */
    @ResponseBody
    @RequestMapping(path = "/app/login")
    public Message appLogin(String appid, String appsecret, String phoneNo, String loginDevice) throws Exception{
        if (StringUtils.isBlank(appid)
                ||StringUtils.isBlank(appsecret)){
            return  new Message(Code.APP_DEVELOP_ERR);
        }

        if (StringUtils.isNotEmpty(phoneNo))
        {
            return appSDKLogin(appid,appsecret,phoneNo,loginDevice);
        } else
        {
            return serverSDKLogin(appid,appsecret);
        }
    }

    /**
     * <desc>
     *    APP SDK_登出(并未清除缓存和进行任何数据库更改).
     * </desc>
     *
     * @param phoneNo 用户手机号
     * @param token 登录Token
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-13
     */
    @ResponseBody
    @RequestMapping(path = "/app/loginOut")
    public Message appLogout(String phoneNo, String token) throws Exception{
        if(StringUtils.isEmpty(phoneNo)||StringUtils.isEmpty(token)) {
            return new Message(Code.NOT_PARAM);
        }
        return new Message(Code.SUCCESS);
    }




    /**
     * <desc>
     *      手机APP用户SDK登录.
     * </desc>
     *
     * @param appid     应用接入凭证
     * @param appsecret 应用接入密钥
     * @param phoneNo   用户手机号或自定义的其它类似手机号的ID
     * @param loginDevice   用户登录设备类型 android/ios
     * @return 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-08
     */
    private Message appSDKLogin(String appid, String appsecret, String phoneNo, String loginDevice) throws  Exception{

        //APP端SDK的认证
        if (StringUtils.isEmpty(loginDevice)) {
            return new Message(Code.NOT_PARAM);
        }

        //尝试从缓存中取出用户信息（若get到，则get时会自动延期）
        SDKAppOldUserInfoCacheVO sdkAppCacheUser = isdkAppOldUserServiceClient.getSDKAppCacheUser(appid, phoneNo);

        if (null == sdkAppCacheUser) {
            //若没有从缓存中查找到用户信息，则尝试从数据库中查找用户信息
            AppOldUserInfoDto userInfo = iAppOldRegisterServiceClient.selectDtoByPhone(phoneNo);
            if (userInfo == null) {
                //数据库中也未查询到用户
                return new Message(Code.NOT_FOUNDPHONE);
            }
            //Token为固定算法，同一个用户反复登录Token不会变化
            String token = UserTokenUtil.tokenEncrypt(userInfo.getUserId(), APP_USER_TOKEN_KEY, SystemTypeEnum.IOS.getType());
            userInfo.setToken(token);
            userInfo.setLoginDevice(APPDeviceTypeEnum.getType(loginDevice));
            if (StringUtils.isEmpty(userInfo.getUserName())) {
                userInfo.setUserName(phoneNo.substring(0, 3) + "****" + phoneNo.substring(phoneNo.length() - 4, phoneNo.length()));
                userInfo.setNickName(userInfo.getUserName());
            }
            //更新登录信息(Token和登录设备类型)
            iAppOldRegisterServiceClient.updateNotNullByAppOldUserInfoDto(userInfo);

            Date now = new Date();
            String nowTimeStr = DateUtil.fomatDate(now,"yyyy-MM-dd HH:mm:ss");
            Integer expiresIn = 7 * 24 * 60 * 60;
            String invalidTime =  (DateUtil.fomatDate(DateUtil.addCurrentTime(7),"yyyy-MM-dd HH:mm:ss"));
            sdkAppCacheUser = new SDKAppOldUserInfoCacheVO();
            sdkAppCacheUser.setUserId(userInfo.getUserId());
            sdkAppCacheUser.setUserName(userInfo.getUserName());
            sdkAppCacheUser.setPhoneNo(userInfo.getUserPhone());
            sdkAppCacheUser.setToken(token);
            sdkAppCacheUser.setAppid(appid);
            sdkAppCacheUser.setExpiresIn(expiresIn);
            sdkAppCacheUser.setCreateTime(nowTimeStr);
            sdkAppCacheUser.setInvalidTime(invalidTime);
            isdkAppOldUserServiceClient.saveSDKAppCacheUser(sdkAppCacheUser);

        }

        JSONObject js = new JSONObject();
        js.put("phoneNo", sdkAppCacheUser.getPhoneNo());
        js.put("token", sdkAppCacheUser.getToken());
        js.put("expiresIn", sdkAppCacheUser.getExpiresIn());
        js.put("userName", sdkAppCacheUser.getUserName());
        js.put("invalidTime", sdkAppCacheUser.getInvalidTime());
        return new Message(Code.SUCCESS, "登录成功", js);
    }


    /**
     * <desc>
     *      SDK服务端登录
     * <desc/>
     * @param appid     应用接入凭证
     * @param appsecret 应用接入密钥
     * @return 标准格式化响应结果
     * @author Biao.R
     * @createDate 2017/11/9
     */
    private Message serverSDKLogin(String appid, String appsecret) {
        try {
            if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(appsecret)) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            //登陆校验及缓存更新
            SDKServerUserCacheVO serverCacheVO = iSDKServerUserServiceClient.sdkServerLogin(appid, appsecret);
            if (serverCacheVO == null) {
                return new Message(Code.APP_DEVELOP_ERR);
            }
            JSONObject js = new JSONObject();
            js.put("token", serverCacheVO.getToken());
            js.put("expiresIn", RedisConstant.SDKSERVER_LOGIN_TIME);
            return new Message(Code.SUCCESS, "登录成功", js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK服务端_SDKAppUserController_serverSDKLogin】登录异常");
        }
    }

}